package com.qianfeng.smartplatform.service.impl;/*
 *@Description:
 *@author:赵健
 *@Date:zjzzz 2022/9/9 9:13
 */

import com.qianfeng.smartplatform.constans.ResultCode;
import com.qianfeng.smartplatform.event.DeviceCommandEvent;
import com.qianfeng.smartplatform.exceptions.AddDataException;
import com.qianfeng.smartplatform.mapper.DeviceMapper;
import com.qianfeng.smartplatform.pojo.SysDevice;
import com.qianfeng.smartplatform.pojo.SysUserInfo;
import com.qianfeng.smartplatform.service.DeviceService;
import com.qianfeng.smartplatform.service.SceneService;
import com.qianfeng.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

@Service
@Transactional
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private SceneService service;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private ApplicationContext applicationContext;


    @Override
    public void addDevice(SysDevice sysDevice) {
        //我们需要获取到当前登录的用户
        SysUserInfo userInfo = SecurityUtils.getLoginUser();
        sysDevice.setBindUserId(userInfo.getUId());
        //如果传递了场景id,我们还得判断当前的场景id属于这个用户
        Long sceneId = sysDevice.getSceneId();
        if (sceneId != null && (-1 > sceneId || 0 == sceneId)) {
            //传递了id不符合要求
            throw new AddDataException("场景不存在", ResultCode.DATA_NOT_EXIST);
        } else if (sceneId != null && sceneId > 0) {
            //传递了一个场景id,判断是否属于当前用户
            service.getSceneById(sceneId);
        }
        //这个设备可能已经被绑定到了其它人身上
        SysDevice device = findByDeviceId(sysDevice.getDeviceId());
        //如果设备已经绑定别人身上,我们就不能绑定了
        Assert.isTrue(device == null || device.getBindUserId().equals(sysDevice.getBindUserId()), () -> {
            throw new AddDataException("设备已经被绑定", ResultCode.DEVICE_ALREADY_BIND);
        });

        if (device == null) {
            //执行绑定操作
            deviceMapper.bindDevice(sysDevice);
        }
    }

    @Override
    public SysDevice findByDeviceId(String id) {
        return deviceMapper.findByDeviceId(id);
    }

    @Override
    public int updateDeviceStatus(String deviceId, int status) {
        return deviceMapper.updateDeviceStatus(deviceId, status);
    }

    @Override
    public void sendCommand(String deviceId, String command) {
        applicationContext.publishEvent(new DeviceCommandEvent(deviceId, command));
    }
}
